/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.al;

import java.rmi.RemoteException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;

/**
 * No timeout mechanism.
 * 
 * @author rah67
 *
 */
public class DefaultAnnotationServer<L, D> implements AnnotationServer<L, D> {
	
	private final InstanceManager<L, D> instanceManager;
	private final Map<Long, AnnotationRequest<L, D>> outstandingRequests;
	private final AtomicLong idCounter;
	
	public DefaultAnnotationServer(InstanceManager<L, D> instanceManager) {
		this(instanceManager, Maps.<Long, AnnotationRequest<L, D>>newConcurrentMap(), new AtomicLong(0L));
	}
	
	@VisibleForTesting
	DefaultAnnotationServer(InstanceManager<L, D> instanceManager,
			Map<Long, AnnotationRequest<L, D>> outstandingRequests,
			AtomicLong idCounter) {
		this.instanceManager = instanceManager;
		this.outstandingRequests = outstandingRequests;
		this.idCounter = idCounter;
	}

	/** {@inheritDoc} */
	@Override
	public void cancelInstanceRequest(long requestId) throws RemoteException {
		AnnotationRequest<L, D> ar = outstandingRequests.remove(requestId);
		ar.cancelRequest();
	}

	/** {@inheritDoc} */
	@Override
	public InstanceForAnnotation<D> requestInstance(long annotatorId) throws RemoteException {
		AnnotationRequest<L, D> ar = instanceManager.requestInstanceFor(annotatorId);
		if (ar == null) {
			// Nothing to annotate
			return null;
		}
		if (outstandingRequests.containsKey(annotatorId)) {
			throw new RemoteException("There is already an outstanding request for this annotator");
		}
		idCounter.incrementAndGet();
		BasicInstanceForAnnotation<D> ifa =
				new BasicInstanceForAnnotation<D>(idCounter.incrementAndGet(), ar.getInstance().getData());
		outstandingRequests.put(annotatorId, ar);
		return ifa;
	}

	/** {@inheritDoc} */
	@Override
	public void storeAnnotation(long requestId, L annotation) throws RemoteException {
		AnnotationRequest<L, D> ar = outstandingRequests.remove(requestId);
		ar.storeAnnotation(annotation);
	}
	
}
